﻿using System.Data;
using System.Reflection;
using T.FAS.Runtime.MF.Entity.ElsaEntity;
using T.ServiceComponent.DAC.Service;

namespace T.FAS.Runtime.MF.Dao.Dao
{
    public class WorkflowInstanceDao : DaoService<WorkflowInstance>
    {
        public override string TableName => "WorkflowDefinitions";
        public override string IDColumnName => "Id";
        public override string DBName => "TFASMF";

        public WorkflowInstance GetInstanceById(string instanceId)
        {
            string sql = @$"SELECT ""Id"", ""DefinitionId"", ""DefinitionVersionId"", ""Version"",
                            ""Status"", ""SubStatus"", ""CorrelationId"", ""Name"", ""IncidentCount"", ""CreatedAt"", ""UpdatedAt"",
                            ""FinishedAt"", ""Data"", ""DataCompressionAlgorithm"", ""IsSystem"", ""ParentWorkflowInstanceId"", 
                            ""TenantId"", ""IsExecuting""
                            FROM ""Elsa"".""WorkflowInstances"" Where ""Id""='{instanceId}'";

            var dataSet = this.DB.ExecuteDataSet(sql);

            if (dataSet != null && dataSet.Tables.Count > 0)
            {
                var dataRow = dataSet.Tables[0].Rows[0];

                var instance = ConvertToObject(base.Columns, dataRow);
                instance.CreatedAt = instance.CreatedAt.AddHours(8);
                instance.UpdatedAt = instance.UpdatedAt.AddHours(8);
                if (instance.FinishedAt.HasValue)
                {
                    instance.FinishedAt = instance.FinishedAt.Value.AddHours(8);
                }
                return instance;
            }
            return null;
        }
        public override WorkflowInstance ConvertToObject(Dictionary<string, PropertyInfo> columns, DataRow row)
        {
            var myCol = new Dictionary<string, PropertyInfo>(base.Columns);

            var data = base.ConvertToObject(myCol, row);

            return data;
        }

    }
}

